<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="设备编号" prop="innerCode">
        <el-input v-model="queryParams.innerCode" placeholder="请输入" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['manage:vm:add']">新建</el-button>
      </el-col>
    </el-row>

    <!-- 设备表格 -->
    <el-table v-loading="loading" :data="vmList">
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column label="设备型号" align="center" prop="vmTypeName" />
      <el-table-column label="详细地址" align="center" prop="addr" />
      <el-table-column label="合作商" align="center" prop="partnerId" />
      <el-table-column label="设备状态" align="center" prop="vmStatus">
        <template #default="scope">
          <dict-tag :options="vm_status" :value="scope.row.vmStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 货道按钮 -->
          <el-button link type="primary" @click="handleGoods(scope.row)" v-hasPermi="['manage:vm:edit']">货道</el-button>
          <el-button link type="primary" @click="handleUpdatePolicy(scope.row)"
            v-hasPermi="['manage:vm:edit']">策略</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['manage:vm:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/修改设备弹层 -->
    <!-- 新增/修改设备弹层 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="vmRef" :model="form" label-width="120px" class="edit-form-inline">
        <!-- 设备编号：系统自动生成 -->
        <el-form-item label="设备编号">
          <span class="view-item">{{ form.innerCode || "系统自动生成" }}</span>
        </el-form-item>

        <!-- 设备型号 -->
        <el-form-item label="选择型号" prop="vmTypeId">
          <el-select v-model="form.vmTypeId" placeholder="请选择设备型号">
            <el-option v-for="type in vmTypeList" :key="type.id" :label="type.name" :value="type.id" />
          </el-select>
        </el-form-item>

        <!-- 设备点位 -->
        <el-form-item label="选择点位" prop="nodeId">
          <el-select v-model="form.nodeId" placeholder="请选择点位">
            <el-option v-for="node in nodeList" :key="node.id" :label="node.addr" :value="node.id" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 策略管理弹层 -->
    <el-dialog title="策略管理" v-model="policyOpen" width="500px" append-to-body>
      <el-form ref="vmRef" :model="form" label-width="80px">
        <el-form-item label="策略" prop="policyId">
          <el-select v-model="form.policyId" placeholder="请选择策略">
            <el-option v-for="item in policyList" :key="item.policyId" :label="item.policyName"
              :value="item.policyId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 货道组件 -->
    <ChannelDialog :goodVisible="goodVisible" :goodData="goodData" @handleCloseGood="handleCloseGood"></ChannelDialog>
  </div>
</template>

<script setup name="Vm">
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { listVm, getVm, addVm, updateVm } from "@/api/manage/vm";
import { listNode } from "@/api/manage/node";
import { listVmType } from "@/api/manage/vmType";
import { listPartner } from "@/api/manage/partner";
import { listRegion } from "@/api/manage/region";
import { listPolicy } from '@/api/manage/policy';
import ChannelDialog from './components/ChannelDialog.vue';

const { proxy } = getCurrentInstance();
const { vm_status } = proxy.useDict('vm_status');

const vmList = ref([]);
const open = ref(false);
const policyOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const nodeList = ref([]);
const vmTypeList = ref([]);
const partnerList = ref([]);
const regionList = ref([]);
const policyList = ref([]);

// 货道相关
const goodVisible = ref(false);
const goodData = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    innerCode: null,
  },
  rules: {
    nodeId: [{ required: true, message: "点位不能为空", trigger: "change" }],
    vmTypeId: [{ required: true, message: "设备型号不能为空", trigger: "change" }],
    partnerId: [{ required: true, message: "合作商不能为空", trigger: "change" }],
    regionId: [{ required: true, message: "所属区域不能为空", trigger: "change" }],
    policyId: [{ required: true, message: "策略不能为空", trigger: "change" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 获取下拉数据
function getNodes() { listNode().then(res => nodeList.value = res.rows); }
function getVmTypes() { listVmType().then(res => vmTypeList.value = res.rows); }
function getPartners() { listPartner().then(res => partnerList.value = res.rows); }
function getRegions() { listRegion().then(res => regionList.value = res.rows); }

/** 查询设备列表 */
function getList() {
  loading.value = true;
  Promise.all([listVm(queryParams.value), listVmType(), listPartner()]).then(([vmRes, vmTypeRes, partnerRes]) => {
    const vmTypeMap = new Map(vmTypeRes.rows.map(t => [t.id, t.name]));
    const partnerMap = new Map(partnerRes.rows.map(p => [p.id, p.name]));
    vmList.value = vmRes.rows.map(item => ({
      ...item,
      vmTypeName: vmTypeMap.get(item.vmTypeId) || '未知类型',
      partnerName: partnerMap.get(item.partnerId) || '未知合作商',
      addr: '北京市海淀区XXX设备'
    }));
    total.value = vmRes.total;
    loading.value = false;
  });
}

// 取消/重置
function cancel() {
  open.value = false;
  policyOpen.value = false;
  reset();
}
function reset() {
  form.value = { id: null, innerCode: null, nodeId: null, vmTypeId: null, partnerId: null, regionId: null, addr: null };
  proxy.resetForm("vmRef");
}
function handleQuery() { queryParams.value.pageNum = 1; getList(); }
function resetQuery() { proxy.resetForm("queryRef"); handleQuery(); }
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备管理";
  getNodes(); getVmTypes(); getPartners(); getRegions();
}
function handleUpdate(row) {
  reset();
  Promise.all([getVm(row.id), listVmType(), listNode(), listPartner(), listRegion()]).then(([vmRes, vmTypeRes, nodeRes, partnerRes, regionRes]) => {
    const vmTypeMap = new Map(vmTypeRes.rows.map(t => [t.id, t.name]));
    const nodeMap = new Map(nodeRes.rows.map(n => [n.id, n.addr]));
    const partnerMap = new Map(partnerRes.rows.map(p => [p.id, p.name]));
    const regionMap = new Map(regionRes.rows.map(r => [r.id, r.name]));
    form.value = {
      ...vmRes.data,
      vmTypeName: vmTypeMap.get(vmRes.data.vmTypeId) || '未知类型',
      nodeName: nodeMap.get(vmRes.data.nodeId) || '未知点位',
      partnerName: partnerMap.get(vmRes.data.partnerId) || '未知合作商',
      regionName: regionMap.get(vmRes.data.regionId) || '未知区域',
      lastSupplyTime: vmRes.data.lastSupplyTime ? new Date(vmRes.data.lastSupplyTime).toLocaleString('zh-CN', { hour12: false }) : '无'
    };
    open.value = true;
    title.value = "设备修改";
    nodeList.value = nodeRes.rows;
    vmTypeList.value = vmTypeRes.rows;
    partnerList.value = partnerRes.rows;
    regionList.value = regionRes.rows;
  });
}

/** 提交表单 */
function submitForm() {
  proxy.$refs["vmRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        const updateData = { id: form.value.id, nodeId: form.value.nodeId, vmTypeId: form.value.vmTypeId, partnerId: form.value.partnerId, regionId: form.value.regionId, addr: form.value.addr, policyId: form.value.policyId };
        updateVm(updateData).then(() => { proxy.$modal.msgSuccess("修改成功"); open.value = false; policyOpen.value = false; getList(); });
      } else {
        addVm(form.value).then(() => { proxy.$modal.msgSuccess("新增成功"); open.value = false; getList(); });
      }
    }
  });
}

/** 策略操作 */
function handleUpdatePolicy(row) {
  form.value.id = row.id; form.value.policyId = row.policyId;
  listPolicy().then(res => { policyList.value = res.rows; policyOpen.value = true; });
}

/** 货道操作 */
function handleGoods(row) { goodVisible.value = true; goodData.value = row; }
function handleCloseGood() { goodVisible.value = false; }

getList();
</script>

<style scoped>
.edit-form-inline .el-form-item {
  width: 50%;
  margin-right: 0;
  display: flex;
}

.edit-form-inline .el-form-item__label {
  text-align: right;
  padding-right: 12px;
}

.edit-form-inline .el-form-item__content {
  flex: 1;
}

.view-item {
  line-height: 40px;
  color: #303133;
}
</style>
